package abg.core.common.util;

import com.alibaba.fastjson2.JSONObject;

import javax.crypto.Cipher;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.math.RoundingMode;
import java.security.KeyFactory;
import java.security.MessageDigest;
import java.security.PrivateKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.util.ArrayList;
import java.util.Base64;
import java.util.Date;
import java.util.Objects;

public class MathKit {

    /**
     * 两个整数之间的数(默认升序)
     *
     * @param o1   一个整数
     * @param o2   另一整数
     * @param sort 排序 "ASC"、"DESC"、NULL(就是升序)
     */
    public static ArrayList<Integer> numberBetweenTwoInt(Object o1, Object o2, String sort) {
        int int1 = Integer.parseInt(o1 + "");
        int int2 = Integer.parseInt(o2 + "");
        ArrayList<Integer> ints = new ArrayList<>();

        if (int1 == int2) {
            ints.add(int1);
            return ints;
        }

        if (int1 < int2) {
            for (int start = int1; start <= int2; start++) {
                ints.add(start);
            }
        }

        if (int1 > int2) {
            for (int start = int2; start <= int1; start++) {
                ints.add(start);
            }
        }

        if ("DESC".equals(sort)) {
            ints.sort((o11, o21) -> o21 - o11);
        }

        return ints;
    }

    /**
     * 加法
     */
    public static BigDecimal add(Object v1, Object v2, int scale) {
        BigDecimal b1 = new BigDecimal(v1.toString());
        BigDecimal b2 = new BigDecimal(v2.toString());
        BigDecimal multiply = b1.add(b2);
        return multiply.setScale(scale, RoundingMode.DOWN);
    }

    /**
     * 减法
     */
    public static BigDecimal sub(Object v1, Object v2, int scale) {
        BigDecimal b1 = new BigDecimal(v1.toString());
        BigDecimal b2 = new BigDecimal(v2.toString());
        BigDecimal multiply = b1.subtract(b2);
        return multiply.setScale(scale, RoundingMode.DOWN);
    }

    /**
     * 乘法
     */
    public static BigDecimal mul(Object v1, Object v2, int scale) {
        BigDecimal b1 = new BigDecimal(v1.toString());
        BigDecimal b2 = new BigDecimal(v2.toString());
        BigDecimal multiply = b1.multiply(b2);
        return multiply.setScale(scale, RoundingMode.DOWN);
    }

    /**
     * 除法
     */
    public static BigDecimal div(Object v1, Object v2, int scale) {
        BigDecimal b1 = new BigDecimal(v1.toString());
        BigDecimal b2 = new BigDecimal(v2.toString());
        return b1.divide(b2, scale, RoundingMode.DOWN);
    }

    /**
     * 计算MD5
     *
     * @param str 需要计算的字符串
     * @return 大写MD5值
     */
    public static String getMD5Upper(String str) {
        try {
            return Objects.requireNonNull(getMD5(str)).toUpperCase();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 计算MD5
     *
     * @param str 需要计算的字符串
     * @return 大写MD5值
     */
    public static String getMD5(String str) {
        String ret;
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.update(str.getBytes());
            ret = new BigInteger(1, md.digest()).toString(16);
            if (ret.length() == 31) {
                ret = "0" + ret;
            } else if (ret.length() == 30) {
                ret = "00" + ret;
            }
            return ret;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }


    private static final String RSA_PUBLIC_KEY =
            "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAnILMnS/Vspt4NkWSV/1x\n" +
                    "a0ldM6nnx2iudxEkSA8pXWv7wsws+HJoFn7Po7gVF2/DtHWg07uC3C9/oZNr1My6\n" +
                    "MoE5qQZH1VHdOrbvvwuyd6a87M2rVy1Qz8acSpEqnCMX07YnhUm5ovlYAIHEP30V\n" +
                    "kJbKkDo4k0mGWcBscUxyfG39rOObHJz4IKrGNaCrWvBc6C8QyaDA9vAcjqnpTuZO\n" +
                    "0vd21N8zsJOmZg/4F+pPXbVGdFQ6HDLk/IIhO9469aka/DAf/hp8chDdER+/tw6c\n" +
                    "d5deqcF1C8Mjo5OIRq0qjOGvFHNDT776krd6syQV7sBz++RkNeXCuVqqyipoDun5\n" +
                    "tQIDAQAB";

    private static final String RSA_PRIVATE_KEY =
            "MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQCcgsydL9Wym3g2\n" +
                    "RZJX/XFrSV0zqefHaK53ESRIDylda/vCzCz4cmgWfs+juBUXb8O0daDTu4LcL3+h\n" +
                    "k2vUzLoygTmpBkfVUd06tu+/C7J3przszatXLVDPxpxKkSqcIxfTtieFSbmi+VgA\n" +
                    "gcQ/fRWQlsqQOjiTSYZZwGxxTHJ8bf2s45scnPggqsY1oKta8FzoLxDJoMD28ByO\n" +
                    "qelO5k7S93bU3zOwk6ZmD/gX6k9dtUZ0VDocMuT8giE73jr1qRr8MB/+GnxyEN0R\n" +
                    "H7+3Dpx3l16pwXULwyOjk4hGrSqM4a8Uc0NPvvqSt3qzJBXuwHP75GQ15cK5WqrK\n" +
                    "KmgO6fm1AgMBAAECggEAKKc0/NNS/7ywYfB6Tc6wKjz5L5U/diVzw8u5D9qYVQLa\n" +
                    "d0PPno0hCk7QImeLWvYV8IbpSnYXTJgt38tKJBE1gC7eyk+uUvObskeYSJiCN+Ag\n" +
                    "jKXzjoZfykh9ikTgu4PGCaDz7QQ0aue3exI55n/YHSF95i6pSWC8vA1mXZuM1VLY\n" +
                    "oDdie47+LjYDUkiVEf/fvGi8HghiAUeAWBG8nQgXkanVcPRqBQft/k93ybRhlIC/\n" +
                    "Ndk4QztM9o0l12isuvKARLJLCY4dBrdBMLugsEff7xlqy8JhurGzoSgotKsiaEbW\n" +
                    "3IMkS3IodQFVEJwsV7o78i8u2wisaA+sTWNpTu6pQQKBgQDNC7tMHPpihBMEuPyL\n" +
                    "ouMDMpa2Qi6DpDCpLwjXfDK5A9oaxWeiB57Ti6yfWeXOgU7bKUXahr+5q8WrgdRJ\n" +
                    "frmBMl/UkTWjgpfEG+g6pWrmHnF6yg/ONLuljeLLN2Mt+4Ojd3qR2GorkHzkegxy\n" +
                    "kcRsC1lARoSlBRIse39t7gYgRQKBgQDDZ3RkjLBZOqjJUUWGzIkPmHGICfzdGNtt\n" +
                    "i4pSOKbahgWJfq3EnmKS90zVI1BxgiY1iWYyR/aSjocRPwvhjz/rAhgfVbel5b0p\n" +
                    "vbKSxTSa1AWqDFcsQpupaadELttwBu85iQ96u3a8pO7tW1iuJbWcWRqm5uPDgecw\n" +
                    "YIIAdFqisQKBgQDA1NSauvHaLj04hsOyikgV3MCRvOHDmWjN4tbc2AdXqcC2xok0\n" +
                    "fxgl+EgqQD/3mfHP+BuibHDoKxultF4xlATe9MHcxYb9M7aIjnoylRhYO68a++Yr\n" +
                    "VbpW8n2kAX27Y7qjw5w4hp8qQyLBN+p24JEpzu5rnSXnj0JNJQNtHZkTRQKBgQCg\n" +
                    "OvkqamNBB+TYEBifDKFndG3ES8xZ0MQ986qc+W94yWVI9eOv0uCp+re6HpccPMjw\n" +
                    "JZbzrCb4zn7bGYO4liqnnrQBHdzV4KlYzQDdcXBNdYafhjcFSCk0pjpOos218zm/\n" +
                    "SDC1R3t5/RUe9USmqK1fY4GDUtl5u8/Dz59KmB6qQQKBgF/Em+cKHTNdGuZHF/qe\n" +
                    "TKGc4YGmwTem7ckX9SlE9jJlrP9b9TW4UzsnAowVjmxChghyWjpNmiNtGRxMfs0l\n" +
                    "0IicIJDRboCysg/DzNYLciEeSODIUhb4h2IGM7OFyt02UEJME8sIbfwkGaHUVJMt\n" +
                    "z9JvQaGUj4dJHmKHVw2cqgCC";

    //私钥解密
    public static String rsaDecrypt(String encryptedText) throws Exception {
        // 1. 指定2048位的私钥字符串
        String privateKeyStr = RSA_PRIVATE_KEY.replaceAll("\\n", ""); // 移除换行符

        // 2. 将私钥字符串转换为PrivateKey对象
        byte[] privateKeyBytes = java.util.Base64.getDecoder().decode(privateKeyStr);
        PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(privateKeyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        PrivateKey privateKey = keyFactory.generatePrivate(keySpec);

        // 3. 解密操作
        Cipher decryptCipher = Cipher.getInstance("RSA");
        decryptCipher.init(Cipher.DECRYPT_MODE, privateKey);

        byte[] encryptedBytes = Base64.getDecoder().decode(encryptedText);
        byte[] decryptedBytes = decryptCipher.doFinal(encryptedBytes);
        return new String(decryptedBytes);
    }

    //解密同时根据参数检查是否已失效
    //return: 正常执行完毕，返回参数对象，否则返回null;
    public static JSONObject rsaIsExpire(String encryptedText) {
        try {
            String str = MathKit.rsaDecrypt(encryptedText);

            JSONObject param = JSONObject.parseObject(str);
            Long expireTime = param.getLong("expireTime");

            long nowTime = new Date().getTime();
            if (nowTime > expireTime) return null;
            return param;
        } catch (Exception e) {
            return null;
        }
    }

}
